<template>
  <section class="app-inner">
    <el-card class="header-card">
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="账号状态">
          <el-select
            placeholder="请选择账号状态"
            filterable
            v-model="queryParams.accountStatus"
            clearable
          >
            <el-option
              v-for="item in postTypes['账号状态']"
              :key="item.code"
              :label="item.name"
              :value="Number(item.code)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门">
          <depart-tree
            style="width: 200px"
            v-model="queryParams.deptNo"
            :departments="departments"
          />
        </el-form-item>
        <el-form-item label="岗位类型">
          <el-select
            placeholder="请选择岗位类型"
            filterable
            v-model="queryParams.positionType"
            clearable
          >
            <el-option
              v-for="item in postTypes['教职工岗位']"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教职工工号">
          <el-input
            v-model="queryParams.number"
            clearable
            placeholder="请输入教职工工号"
          ></el-input>
        </el-form-item>
        <el-form-item label="教职工姓名">
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入教职工姓名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit(1)">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="header-card card-flex">
      <el-button v-if="checkAuthority('/teacherInfo/add')" type="primary" @click="addTeachInfo">新增人员</el-button>
      <el-button v-if="checkAuthority('/teacherInfo/download')" type="primary" @click="downloadTemplate">下载模板</el-button>
      <el-upload
        style="display: inline; margin-left: 10px"
        action="string"
        :show-file-list="false"
        :http-request="handleBatchImport"
        :before-upload="beforeUpload"
      >
        <el-button v-if="checkAuthority('/teacherInfo/batch')" type="primary">批量导入</el-button>
      </el-upload>
      <el-button
        v-if="checkAuthority('/teacherInfo/export')"
        type="primary"
        style="display: inline; margin-left: 10px"
        @click="handleExport"
        >批量导出</el-button
      >
      <div v-if="checkAuthority('/eyes')" class="switch-btn cursor iconfont" :class="[isShow ? 'icon-biyan': 'icon-yanjing']" @click="handleClickIsShow"></div>
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" center>
        <el-table-column label="序号">
          <template slot-scope="scope">
            {{ pageSize * (currentPage - 1) + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="number" label="工号" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="deptName" label="部门" />
        <el-table-column prop="contact" label="联系方式">
          <template v-slot='{row}'>
            {{ !isShow ? $options.filters.cellularPhone(row.contact) : row.contact || '--' }}
            <!-- {{row.contact | cellularPhone}} -->
          </template>
        </el-table-column>
        <el-table-column prop="positionTypeName" label="岗位类型" />
        <el-table-column prop="genderName" label="性别" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="accountStatus" label="账号状态">
          <template slot-scope="{ row }">
            <div v-if="row.account">
              <el-switch
                v-model="row.accountStatus"
                @change="handleSwitchChange(row.accountStatus, row.id)"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#C0C4CC"
              >
              </el-switch>
            </div>
            <div v-else></div>
          </template>
        </el-table-column>
        <el-table-column label="照片">
          <template slot-scope="scope" v-if="scope.row.imageUrl">
            <el-image
              style="width: 100px; height: 100px"
              :src="`/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`"
              :preview-src-list="[
                `/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`,
              ]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="checkAuthority('/select')"
              @click.native.prevent="infoSeeing(scope.row)"
              type="text"
              size="small"
              >查看</el-button
            >
            <el-button
              v-if="checkAuthority('/teacherInfo/update')"
              @click.native.prevent="infoEdit(scope.row)"
              type="text"
              size="small"
              >编辑</el-button
            >
            <el-button
              v-if="checkAuthority('/teacherInfo/delete')"
              @click.native.prevent="infoDel(scope.row)"
              type="text"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="total, prev, pager, next"
        @current-change="pageHandleChange"
        :current-page="currentPage"
        :total="totalPageNum"
      ></el-pagination>
    </el-card>
    <addTeachInfo
      :infoData="infoData"
      :deptData="departments"
      :addTeachForm="addTeachForm"
      :data="addTeachFormData"
      v-if="addTeachForm.flag"
      @closeaddTeachForm="addTeachForm.flag = false"
    />
    <teachInfoForm
      :teachForm="teachForm"
      :data="lookTeachFormData"
      @closeteachForm="teachForm.flag = false"
    />
  </section>
</template>

<script>
import teachInfoForm from './components/teachInfoForm'
import addTeachInfo from './components/addTeachInfo'
import { queryPage, downloadTemplate, queryDeptListBySchoolNo, deleteTeach, batchImport, batchExportTeacher, updateTeacherAccountStatus, userNoIsBinding } from '@/views/children/basic/js/teacherInfo'
import { sepDataDicInfoQuery } from '@/views/children/basic/js/controllerInfo'
import DepartTree from './components/departTree'
import { decrypt } from '@/utils/crypto'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限
export default {
  name: 'teacherInfo',
  components: {
    teachInfoForm,
    addTeachInfo,
    DepartTree
  },
  provide () {
    return {
      handleSearch: this.onSubmit
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  data () {
    return {
      pageSize: 10,
      currentPage: 1,
      totalPageNum: 0,
      queryParams: {
        accountStatus: 1,
        deptNo: '',
        name: '',
        number: '',
        positionType: ''
      },
      infoData: {},
      // 部门
      departments: [],
      // 岗位类型
      postTypes: [],
      // 表格数据
      tableData: [],
      // 表头信息
      columns: [
        { label: '序号', prop: 'id' }, { label: '工号', prop: 'schoolId' }, { label: '姓名', prop: 'schoolName' },
        { label: '部门', prop: 'schoolAddress' }, { label: '联系方式', prop: 'contacts' }, { label: '岗位类型', prop: 'contactInformation' },
        { label: '性别', prop: 'subCampus' }, { label: '账号', prop: 'subCampus' }, { label: '账号状态', prop: 'subCampus' }, { label: '照片', prop: 'photo' }
      ],
      // 查看
      teachForm: {
        flag: false,
        title: ''
      },
      lookTeachFormData: {},
      addTeachFormData: {},
      // 新增
      addTeachForm: {
        flag: false,
        title: ''
      },
      loading: null,
      defaultProps: {
        children: 'children',
        label: 'deptName'
      },
      isShow: false
    }
  },
  methods: {
    checkAuthority,
    handleClickIsShow () {
      this.isShow = !this.isShow
    },
    // 查询
    onSubmit (pageNum = 0) {
      this.currentPage = pageNum ? 1 : this.currentPage
      let params = {
        accountStatus: this.queryParams.accountStatus,
        deptNo: this.queryParams.deptNo,
        positionType: this.queryParams.positionType,
        name: this.queryParams.name,
        number: this.queryParams.number,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      queryPage(params).then(res => {
        let data = JSON.parse(decrypt(res.data))
        if (data) {
          this.totalPageNum = data.total
          this.tableData = data.records
        }
      })
    },
    // 下载
    downloadTemplate () {
      downloadTemplate()
    },
    async handleBatchImport (params) {
      // 批量导入
      try {
        const formData = new FormData()
        formData.append('file', params.file)
        const res = await batchImport(formData)
        if (res.code === 0) {
          this.$message.success('导入成功！')
          this.onSubmit(1)
        }
      } catch (e) { }
    },
    async handleExport () {
      // 批量导出excel
      try {
        const res = await batchExportTeacher(
          {
            ...this.queryParams,
            downloadType: 0, // 0 导出压缩包zip 1 execl
            pageNum: this.currentPage,
            pageSize: this.pageSize
          }
        )
        if (res.code === 0) {
          this.$message.success('导出成功！')
        } else {
          this.$message.error('导出失败！')
        }
      } catch (e) {
        this.$message.error('导出失败！')
      }
    },
    beforeUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const zipType = file.name.split('.')[1] === 'zip'
      const isLt2M = file.size / 1024 / 1024 < 200
      if (!extension && !extension2 && !zipType) {
        this.$message.warning('导入模板只能是xls、xlsx、zip格式!')
        return false
      } else if (!isLt2M) {
        this.$message.warning('导入模板大小不能超过 200MB!')
        return false
      } else {
        this.loading = this.$loading({
          lock: true,
          text: '正在导入',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        })
        return true
      }
    },
    async handleSwitchChange (status, id) {
      // 账号状态启用/停用
      try {
        const res = await updateTeacherAccountStatus({
          accountStatus: status,
          id
        })
        if (res.code === 0) {
          this.$message.success('账号状态更新成功！')
          this.onSubmit()
        }
      } catch (e) { }
    },
    // 新增教职工信息
    addTeachInfo () {
      this.addTeachForm.flag = true
      this.addTeachForm.title = '新增教职工信息'
      this.addTeachFormData = {
        isCreateAccount: 1,
        cardType: '1',
        nationality: '156'
      }
    },
    // 查看
    infoSeeing (data) {
      this.teachForm.flag = true
      this.teachForm.title = data.title
      this.lookTeachFormData = data
    },
    // 编辑
    infoEdit (data) {
      this.addTeachForm.flag = true
      this.addTeachForm.title = '编辑教职工信息'
      this.addTeachFormData = Object.assign(data, {
        nativePlace: this.setRegionTextToCode(data.nativePlace),
        birthPlace: this.setRegionTextToCode(data.birthPlace),
        residenceLocation: this.setRegionTextToCode(data.residenceLocation)
      })
    },
    setRegionTextToCode (region) {
      if (region) {
        return region.split(',')
      }
    },
    // 删除
    infoDel (row) {
      this.$confirm('此操作将删除该教职工信息 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await userNoIsBinding({ userNo: row.no, userType: 0 })
        if (res.data) {
          this.$confirm(' 已绑定沪学通小程序，是否确认删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteTeach(row.id)
          })
        } else {
          this.deleteTeach(row.id)
        }
      })
    },
    async deleteTeach (id) {
      await deleteTeach(id)
      this.$message.success('删除成功')
      this.onSubmit()
    },
    // 分页
    pageHandleChange (page) {
      this.currentPage = page
      this.onSubmit()
    },
    async sepDataDicInfoQuery () {
      const data = await sepDataDicInfoQuery()
      if (data) {
        this.infoData = data.data
        this.postTypes = data.data
      }
    },
    queryDeptListBySchoolNo () {
      queryDeptListBySchoolNo({}).then(res => {
        if (res.code === 0) {
          this.departments = res.data
        }
      })
    },
    init () {
      this.sepDataDicInfoQuery()
      this.queryDeptListBySchoolNo()
      this.onSubmit()
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style lang="scss" scoped>
.app-inner {
  .header-card {
    margin-bottom: 10px;
    .my-tree {
      padding: 10px 15px 10px 0;
      border-radius: 6px;
      border: 1px solid #dcdfe6;
      ::v-deep {
        .el-tree__empty-block {
          width: 190px;
          min-height: 32px;
        }
      }
    }
  }
  .el-pagination {
    text-align: center;
    display: block;
    margin: 10px auto;
  }
}
</style>
